package com.ll.blog.Exception;
import com.ll.blog.common.ApiResponse;
import com.ll.blog.contant.ExceptionEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Priority;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
import java.util.stream.Collectors;


@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(Exception.class)
    public ApiResponse handleException(Exception e){
        log.error("Default Exception",e);
        return ApiResponse.error(ExceptionEnum.SYSTEM_ERROR);
    }
    @ExceptionHandler(BlogException.class)
    public ApiResponse handleBlogException(BlogException e){
        log.error("custom Exception",e);
        return ApiResponse.error(e.getCode(),e.getMessage());
    }


    @ExceptionHandler(ConstraintViolationException.class)
    public ApiResponse ConstraintViolationException(ConstraintViolationException e){
        log.error("MethodArgumentNotValidException",e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        String message = violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(","));
        return ApiResponse.error(ExceptionEnum.PARAMS_ERROR.getCode(),message);
    }
}
